<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { getTravelNoteList } from '../../api/travelNote'
import { getTravelPlans } from '../../api/travelPlan'
import { View, ChatRound, Star, Location, Edit } from '@element-plus/icons-vue'

const router = useRouter()
const route = useRoute()

// Tab切换：游记 / 旅行计划
const activeTab = ref('notes')

// 游记列表（通过API动态获取）
const notes = ref([])
const loadingNotes = ref(false)

const fetchNotes = async () => {
  loadingNotes.value = true
  try {
    const result = await getTravelNoteList({
      page: 1,
      pageSize: 100,
      status: 'approved',
      visibility: 'public',
      order_by: 'published_at',
      order: 'DESC'
    })

    if (result && result.success && result.data && Array.isArray(result.data.list)) {
      // 将后端返回字段映射为页面所需字段名
      notes.value = result.data.list.map(note => ({
        id: note.id,
        title: note.title,
        cover: note.cover_image,
        content: note.content,
        author: note.author?.nickname || note.author?.username || '匿名',
        avatar: note.author?.avatar || 'https://picsum.photos/100/100?random=1',
        createTime: note.published_at || note.start_date || note.created_at,
        cityName: note.city,
        viewCount: note.view_count,
        commentCount: note.comment_count,
        likeCount: note.like_count,
        visibility: note.visibility,
        status: note.status
      }))
    } else {
      notes.value = []
    }
  } catch (e) {
    console.error('获取游记列表失败:', e)
    notes.value = []
  } finally {
    loadingNotes.value = false
  }
}

// 仅展示：设置为公开且审核通过的游记（双重保险）
const publishedNotes = computed(() => {
  return notes.value.filter(note => note.visibility === 'public' && note.status === 'approved')
})

  const goToNoteDetail = (id) => {
    router.push({ path: `/travel-note/${id}`, query: { readonly: '1' } })
  }

const createNewNote = () => {
  router.push('/travel-note/new')
}

const getSummary = (html) => {
  if (!html) return ''
  const tmp = document.createElement('div')
  tmp.innerHTML = html
  const text = tmp.textContent || tmp.innerText || ''
  return text.trim().slice(0, 120)
}

// 旅行计划列表（通过API动态获取）
const plans = ref([])
const loadingPlans = ref(false)

const fetchPlans = async () => {
  loadingPlans.value = true
  try {
    const list = await getTravelPlans()
    plans.value = Array.isArray(list) ? list : []
  } catch (e) {
    console.error('获取旅行计划失败:', e)
    plans.value = []
  } finally {
    loadingPlans.value = false
  }
}

onMounted(() => {
  const tab = route.query?.tab
  activeTab.value = tab === 'plans' ? 'plans' : 'notes'
  fetchNotes()
  fetchPlans()
})

// 展示：所有公开的旅行计划（不按审核状态过滤，仅浏览）
const publicPlans = computed(() => {
  return plans.value.filter(plan => !!plan.isPublic)
})

const goToPlanDetail = (id) => {
  // 社区入口：仅浏览模式，传入只读标记
  router.push({
    path: `/travel-plan/${id}`,
    query: { readonly: '1' }
  })
}
</script>

<template>
  <div class="community-container">
    <div class="page-header">
      <h1>旅行社区</h1>
      <el-button v-if="activeTab === 'notes'" type="primary" @click="createNewNote">
        <el-icon><Edit /></el-icon>发布游记
      </el-button>
    </div>

    <!-- 顶部Tab切换 -->
    <el-tabs v-model="activeTab" class="community-tabs">
      <el-tab-pane label="游记" name="notes">
        <!-- 游记列表（仅公开且审核通过） -->
        <div class="note-list">
          <el-card
            v-for="note in publishedNotes"
            :key="note.id"
            class="note-card"
            @click="goToNoteDetail(note.id)"
          >
            <div class="note-header">
              <div class="note-user">
                <el-avatar :size="40" :src="note.avatar"></el-avatar>
                <div class="note-user-info">
                  <div class="note-username">{{ note.author }}</div>
                  <div class="note-time">{{ note.createTime }}</div>
                </div>
              </div>
            </div>

            <h3 class="note-title">{{ note.title }}</h3>
            <p class="note-summary">{{ getSummary(note.content) }}</p>

            <div class="note-cover" v-if="note.cover">
              <el-image :src="note.cover" fit="cover" class="cover-image" />
            </div>

            <div class="note-footer">
              <div class="note-stats">
                <span><el-icon><View /></el-icon> {{ note.viewCount ?? note.views ?? 0 }}</span>
                <span><el-icon><ChatRound /></el-icon> {{ note.commentCount ?? note.comments ?? 0 }}</span>
                <span><el-icon><Star /></el-icon> {{ note.likeCount ?? note.likes ?? 0 }}</span>
              </div>
              <div class="note-location" v-if="note.cityName">
                <el-icon><Location /></el-icon> {{ note.cityName }}
              </div>
            </div>
          </el-card>

          <div v-if="!publishedNotes.length" class="empty-tip">
            暂无公开并审核通过的游记，去发布第一篇吧～
          </div>
        </div>
      </el-tab-pane>

      <el-tab-pane label="旅行计划" name="plans">
        <!-- 旅行计划列表（仅审核通过，无点赞收藏评论） -->
        <div class="plan-list">
          <el-card
            v-for="plan in publicPlans"
            :key="plan.id"
            class="plan-card"
            shadow="hover"
            @click="goToPlanDetail(plan.id)"
          >
            <div class="plan-cover" v-if="plan.coverImage">
              <el-image :src="plan.coverImage" fit="cover" class="plan-image" />
              <div class="plan-days" v-if="plan.days">{{ plan.days }}天</div>
            </div>
            <div class="plan-info">
              <h3 class="plan-title">{{ plan.title }}</h3>
              <div class="plan-meta">
                <span v-if="plan.cityName"><el-icon><Location /></el-icon> {{ plan.cityName }}</span>
                <span v-if="plan.startDate">出发：{{ plan.startDate }}</span>
                <span v-else-if="plan.created_at">创建：{{ plan.created_at }}</span>
              </div>
              <div class="plan-browse-tip">仅浏览（无点赞/收藏/评论）</div>
            </div>
          </el-card>

          <div v-if="loadingPlans && activeTab === 'plans'" class="empty-tip">
            正在加载旅行计划...
          </div>

          <div v-else-if="!publicPlans.length" class="empty-tip">
            暂无公开的旅行计划
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<style scoped>
.community-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h1 {
  margin: 0;
  font-size: 24px;
  color: #303133;
}

.community-tabs {
  margin-bottom: 10px;
}

.note-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.note-card {
  cursor: pointer;
  transition: transform 0.2s;
}

.note-card:hover {
  transform: translateY(-3px);
}

.note-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.note-user {
  display: flex;
  align-items: center;
  gap: 10px;
}

.note-user-info {
  display: flex;
  flex-direction: column;
}

.note-username {
  font-weight: bold;
  color: #303133;
}

.note-time {
  font-size: 12px;
  color: #909399;
}

.note-title {
  margin: 0 0 10px;
  font-size: 18px;
  color: #303133;
}

.note-summary {
  color: #606266;
  margin-bottom: 15px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
}

.note-cover {
  margin-bottom: 15px;
}

.cover-image {
  width: 100%;
  height: 240px;
  border-radius: 4px;
  object-fit: cover;
}

.note-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: #909399;
  font-size: 14px;
}

.note-stats {
  display: flex;
  gap: 15px;
}

.note-stats span {
  display: flex;
  align-items: center;
  gap: 4px;
}

.note-location {
  display: flex;
  align-items: center;
  gap: 4px;
}

.empty-tip {
  text-align: center;
  color: #909399;
  padding: 40px 0;
}

/* 旅行计划样式（简化为仅浏览卡片） */
.plan-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.plan-card {
  cursor: pointer;
}

.plan-cover {
  position: relative;
  margin-bottom: 12px;
}

.plan-image {
  width: 100%;
  height: 220px;
  border-radius: 4px;
  object-fit: cover;
}

.plan-days {
  position: absolute;
  bottom: 10px;
  right: 10px;
  background: rgba(0,0,0,0.6);
  color: #fff;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.plan-title {
  margin: 0 0 6px;
  font-size: 18px;
  color: #303133;
}

.plan-meta {
  display: flex;
  gap: 12px;
  color: #909399;
  font-size: 14px;
  align-items: center;
}

.plan-browse-tip {
  margin-top: 8px;
  font-size: 12px;
  color: #a0a0a0;
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }
}
</style>